# conftest.py
import allure
import pytest
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
from datetime import datetime




BASE_URL = "http://host.docker.internal:8802"
def _chrome_opts():
    opts = Options()
    opts.add_argument("--headless")
    opts.add_argument("--disable-gpu")
    opts.add_argument("--window-size=1920,1080")
    opts.add_argument("--log-level=3")
    opts.add_experimental_option("excludeSwitches", ["enable-logging"])
    return opts
# def _chrome_opts():
#     opts = Options()
#     # headless（使用新模式兼容性好）
#     opts.add_argument("--headless=new")
#     # Docker/CI 必备
#     opts.add_argument("--no-sandbox")
#     opts.add_argument("--disable-dev-shm-usage")
#     opts.add_argument("--disable-gpu")
#     opts.add_argument("--window-size=1920,1080")
#     opts.add_argument("--log-level=3")
#     opts.add_experimental_option("excludeSwitches", ["enable-logging"])
#     return opts
# ---------- 全局浏览器 ----------
# @pytest.fixture(scope="module")
# def browser():
#     options = Options()
#     options.add_argument("--disable-blink-features=AutomationControlled")
#     driver = webdriver.Chrome(options=options)
#     driver.maximize_window()
#     yield driver
#     driver.quit()          # 只有这里 quit 一次

# ---------- 已登录 ----------
@pytest.fixture(scope="module")
def logged_driver():
    driver = webdriver.Chrome(options=_chrome_opts())
    # driver = webdriver.Chrome()
    driver.implicitly_wait(5)
    from page.login_page import LoginPage
    LoginPage(driver).login("admin", "admin")
    yield driver
    try:
        driver.quit()
    except Exception:
        pass
# ---------- 干净浏览器（给登录用例） ----------
@pytest.fixture(scope="function")
def login_driver():
    """每次用例都开全新浏览器（登录专用）"""
    # options = Options()
    # options.add_argument("--disable-blink-features=AutomationControlled")
    driver = webdriver.Chrome(options=_chrome_opts())
    driver.implicitly_wait(5)
    # driver.maximize_window()
    yield driver
    try:
        driver.quit()
    except Exception:
        pass

# @pytest.fixture(scope="function")
# def driver(login_driver):
#     return login_driver        # 登录用例用 login_driver

@pytest.fixture(scope="session")
def token():
    login_url = f"{BASE_URL}/wemedia/MEDIA/wemedia/login/in"
    login_data = {"name": "lisi1", "password": "admin"}
    resp = requests.post(login_url, json=login_data)
    assert resp.status_code == 200
    json_data = resp.json()
    assert json_data["code"] == 0
    _token = json_data["data"]["token"]
    print("登录成功，token =", _token)
    return _token

@pytest.fixture()
def driver_kwargs(driver_kwargs):
    """覆盖默认的 driver_kwargs"""
    # 移除冲突参数
    driver_kwargs.pop("desired_capabilities", None)
    driver_kwargs.pop("service_log_path", None)  # 新增：移除 service_log_path

    # 添加自定义选项
    chrome_options = Options()
    chrome_options.set_capability("browserVersion", "138")

    driver_kwargs.update({"options": chrome_options})
    return driver_kwargs

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()

    if rep.when == "call" and rep.failed:
        # 尝试从 item.funcargs 中找到可用的 driver
        driver = None
        for key in ("login_driver", "logged_driver", "driver", "browser"):
            driver = item.funcargs.get(key)
            if driver:
                break

        if driver:
            try:
                os.makedirs("./screenshots", exist_ok=True)
                time_str = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
                screenshot_path = os.path.join("./screenshots", f"{item.name}_{time_str}.png")
                driver.save_screenshot(screenshot_path)
                with open(screenshot_path, "rb") as f:
                    allure.attach(f.read(), name="失败截图", attachment_type=allure.attachment_type.PNG)
                print(f"测试失败，截图保存到：{screenshot_path}")
            except Exception as e:
                print("截图失败：", e)
        else:
            print("测试失败，但未找到 driver 实例，无法截图。")
# @pytest.hookimpl(hookwrapper=True)
# def pytest_runtest_makereport(item, call):
#     # 执行测试，获取结果
#     outcome = yield
#     rep = outcome.get_result()
#     if rep.when == "call" and rep.failed:
#         print("测试失败.....")
#         driver = item.funcargs.get("browser_driver")
#         if driver:
#             os.makedirs("./screenshots", exist_ok=True)
#             time_str = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
#             screenshot_path = os.path.join("./screenshots", f"{item.name}_{time_str}.png")
#             driver.save_screenshot(screenshot_path)
#             # 把截图挂载到Allure报告
#             with open(screenshot_path, "rb") as f:
#                 allure.attach(f.read(), "失败截图", attachment_type=allure.attachment_type.PNG)
#             print(f"测试失败，截图保存到：{screenshot_path}")